//
// Created by mouse on 2019/11/12.
//

#ifndef NODEMCU_CONFIG_H
#define NODEMCU_CONFIG_H

#include <Esp.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESPAsyncWebServer.h>
#include <ESPAsyncDNSServer.h>
#include <FS.h>
#include <ArduinoJson.h>
#include <Scheduler.h>
#include "Utils.h"
#include "app_log.h"

#define CONFIG_DIR_PATH "/config"
#define WEB_DIR_PATH "/web"

#define DOMAIN_NAME "genghe.laoshuzi.top"
#define AP_SSID "GengHe-" + String(ESP.getChipId())
#define AP_PASSWORD "12345678"
#define AP_STATIC_IP "192.168.0.1"
#define AP_STATIC_GW "192.168.0.254"
#define AP_STATIC_SN "255.255.255.0"

extern bool configMode;
extern bool formatFileSystem;

class ConfigInfo
{
public:
    char sta_wifi_ssid[32] = "";
    char sta_wifi_password[32] = "";

    char mqtt_server[32] = "gm.laoshuzi.top";
    char mqtt_port[6] = "18383";
    char mqtt_username[16] = "admin";
    char mqtt_password[32] = "admin";

    uint32_t info_version_code = 0;
    char device_key[32] = "";
    int product_key_size = 0;
    char product_keys[8][32];

    static void loadConfigFile(ConfigInfo *configInfo);

    static void saveConfigFile(ConfigInfo *configInfo);

    static void printConfigInfo();
};

extern ConfigInfo *configInfo;

class ConfigServer
{
private:
    AsyncWebServer *_webServer;
    AsyncDNSServer *_dnsServer;

public:
    ConfigServer();

    ~ConfigServer();

    AsyncWebServer *getWebServer();

    AsyncDNSServer *getDNSServer();

    void start();

    void stop();
};

class ConfigTask : public Task
{
private:
    ConfigServer *_configServer;

    void initConfig();

    void initNetwork();

    void setupConfigMode();

    void setupStaMode();

protected:
    void setup() override
    {
        initNetwork();
    }

    void loop() override
    {
        LOG_DEBUG("Free Heap: %d bytes\r\n", ESP.getFreeHeap());
        delay(10000);
    }

public:
    bool formatFileSystem;
    bool configMode;

    ConfigTask(bool formatFileSystem = false, bool configMode = false);

    ~ConfigTask();
};

namespace WifiUtils {

    wl_status_t wifiConnect(String ssid, String password, uint16_t timeout);

    void printWifi();
}

#endif //NODEMCU_CONFIG_H
